package test.file.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class FileUtils {
	
	/**
	 * 一次读取文件中所有内容
	 * @param fileName
	 * @return
	 */
	public static String readToString(String fileName) {  
        String encoding = "UTF-8";
        File file = new File(fileName);  
        Long filelength = file.length();  
        byte[] filecontent = new byte[filelength.intValue()];  
        try {  
            FileInputStream in = new FileInputStream(file);  
            in.read(filecontent);  
            in.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        try {  
            return new String(filecontent, encoding);  
        } catch (UnsupportedEncodingException e) {  
            System.err.println("The OS does not support " + encoding);  
            e.printStackTrace();  
            return null;  
        }  
    }  
	
	/**
	 * 逐行读取文件中内容方法1
	 * @param fin
	 * @throws IOException
	 */
	public static List<String> readFile1(File fin) throws IOException {
		FileInputStream fis = new FileInputStream(fin);
		List<String> result = new ArrayList<String>();
	 
		//Construct BufferedReader from InputStreamReader
		BufferedReader br = new BufferedReader(new InputStreamReader(fis));
	 
		String line = null;
		while ((line = br.readLine()) != null) {
			//System.out.println(line);
			result.add(line);
		}
	 
		br.close();
	        fis.close();
	        
	    return result;
	}
	
	/**
	 * 逐行读取文件中内容方法2
	 * @param fin
	 * @throws IOException
	 */
	public static List<String> readFile2(File fin) throws IOException {
		// Construct BufferedReader from FileReader
		BufferedReader br = new BufferedReader(new FileReader(fin));
		List<String> result = new ArrayList<String>();
	 
		String line = null;
		while ((line = br.readLine()) != null) {
			//System.out.println(line);
			result.add(line);
		}
	 
		br.close();
		return result;
	}

}
